package com.ct.dao.searching.hibernate;

import org.hibernate.transform.ResultTransformer;

import java.util.List;
import java.util.ArrayList;

/**
 * Created by IntelliJ IDEA.
 * User: nmkravchenko
 * Date: 22.10.2009
 * Time: 18:13:41
 * To change this template use File | Settings | File Templates.
 */
public class CountTransformer  implements ResultTransformer {
    private static final String DEFAULT_ALIAS = "row_count";
    private int count = -1;
    private String alias;

    public CountTransformer() { this(DEFAULT_ALIAS); }
    public CountTransformer(String anAlias) { alias = anAlias; }

    public List transformList(List aList) {
        if (aList != null && !aList.isEmpty()) {

            // first check that array returned as a results
            // second there is two cases first - explicit using count in select query,
            // second case - there is some situations then results still array even they should'nt be array
            if ( aList.get(0) != null && aList.get(0).getClass().isArray()
                    && (count != -1 || ((Object[])aList.get(0)).length == 1 )) {
                List newCollection = new ArrayList(aList.size());
                for (Object elem : aList) {
                    if (elem != null) {
                        Object[] row = (Object[]) elem;
                        if ((row.length == 2 && count != -1) || row.length == 1) {
                            newCollection.add(row[0]);
                        } else {
                            Object[] newRow = new Object[row.length - 1];
                            System.arraycopy(row, 0, newRow, 0, row.length - 1);
                            newCollection.add(newRow);
                        }
                    }
                }
                return newCollection;
            }
        }
        return aList;
    }

    public Object transformTuple(Object[] aTuple, String[] anAliases) {
        if (count == -1) {
            if (aTuple != null && (aTuple.length != 0) && anAliases != null && alias.equals(anAliases[anAliases.length - 1])) {
                count = ((Long)aTuple[aTuple.length - 1]).intValue();
            }
        }
        return aTuple;
    }

    public int getCount() { return count;}

}
